package com.example.managemyself.data.network;

import android.util.Log;
import com.example.managemyself.config.AppConfig;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 天气API服务类
 */
public class WeatherApiService {
    private static final String TAG = "WeatherApiService";
    
    private static WeatherApiService instance;
    private final OkHttpClient client;
    private final AppConfig appConfig;
    
    /**
     * 天气信息回调接口
     */
    public interface WeatherCallback {
        void onSuccess(WeatherInfo weatherInfo);
        void onError(String error);
    }
    
    /**
     * 城市信息数据类
     */
    public static class CityInfo {
        private String name;
        private String province;
        private String code;
        
        public CityInfo(String name, String province, String code) {
            this.name = name;
            this.province = province;
            this.code = code;
        }
        
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        
        public String getProvince() { return province; }
        public void setProvince(String province) { this.province = province; }
        
        public String getCode() { return code; }
        public void setCode(String code) { this.code = code; }
        
        @Override
        public String toString() {
            return name + " (" + province + ")";
        }
    }
    
    /**
     * 天气信息数据类
     */
    public static class WeatherInfo {
        private String place;
        private String temperature;
        private String humidity;
        private String windDirection;
        private String windScale;
        private String windSpeed;
        private String precipitation;
        
        public String getPlace() { return place; }
        public void setPlace(String place) { this.place = place; }
        
        public String getTemperature() { return temperature; }
        public void setTemperature(String temperature) { this.temperature = temperature; }
        
        public String getHumidity() { return humidity; }
        public void setHumidity(String humidity) { this.humidity = humidity; }
        
        public String getWindDirection() { return windDirection; }
        public void setWindDirection(String windDirection) { this.windDirection = windDirection; }
        
        public String getWindScale() { return windScale; }
        public void setWindScale(String windScale) { this.windScale = windScale; }
        
        public String getWindSpeed() { return windSpeed; }
        public void setWindSpeed(String windSpeed) { this.windSpeed = windSpeed; }
        
        public String getPrecipitation() { return precipitation; }
        public void setPrecipitation(String precipitation) { this.precipitation = precipitation; }
        
        @Override
        public String toString() {
            return "WeatherInfo{" +
                    "place='" + place + '\'' +
                    ", temperature='" + temperature + '\'' +
                    ", humidity='" + humidity + '\'' +
                    ", windDirection='" + windDirection + '\'' +
                    ", windScale='" + windScale + '\'' +
                    ", windSpeed='" + windSpeed + '\'' +
                    ", precipitation='" + precipitation + '\'' +
                    '}';
        }
    }
    
    private WeatherApiService() {
        this.client = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build();
        this.appConfig = AppConfig.getInstance();
    }
    
    public static synchronized WeatherApiService getInstance() {
        if (instance == null) {
            instance = new WeatherApiService();
        }
        return instance;
    }
    
    /**
     * 获取天气信息
     */
    public void getWeatherInfo(String province, String city, WeatherCallback callback) {
        String apiUrl = appConfig.getWeatherApiUrl();
        String apiId = appConfig.getWeatherApiId();
        String apiKey = appConfig.getWeatherApiKey();
        
        if (apiUrl == null || apiId == null || apiKey == null) {
            callback.onError("天气API配置未设置");
            return;
        }
        
        HttpUrl.Builder urlBuilder = HttpUrl.parse(apiUrl).newBuilder()
                .addQueryParameter("id", apiId)
                .addQueryParameter("key", apiKey)
                .addQueryParameter("sheng", province)
                .addQueryParameter("place", city);
        
        String url = urlBuilder.build().toString();
        Log.d(TAG, "Weather API request URL: " + url);
        
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Accept", "application/json")
                .addHeader("User-Agent", "ManageMyself-Android/1.0")
                .build();
        
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "天气API请求失败", e);
                callback.onError("网络请求失败: " + e.getMessage());
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    if (!response.isSuccessful()) {
                        callback.onError("API请求失败: HTTP " + response.code());
                        return;
                    }
                    
                    String responseBody = response.body().string();
                    Log.d(TAG, "Weather API response: " + responseBody);
                    
                    WeatherInfo weatherInfo = parseWeatherResponse(responseBody);
                    if (weatherInfo != null) {
                        callback.onSuccess(weatherInfo);
                    } else {
                        callback.onError("解析天气数据失败");
                    }
                    
                } catch (Exception e) {
                    Log.e(TAG, "处理天气API响应失败", e);
                    callback.onError("处理响应失败: " + e.getMessage());
                }
            }
        });
    }
    
    /**
     * 解析天气API响应
     */
    private WeatherInfo parseWeatherResponse(String responseBody) {
        try {
            JSONObject jsonObject = new JSONObject(responseBody);
            
            if (jsonObject.has("msg")) {
                String msg = jsonObject.getString("msg");
                if (!msg.isEmpty() && !msg.equals("success")) {
                    Log.e(TAG, "天气API返回错误: " + msg);
                    return null;
                }
            }
            
            WeatherInfo weatherInfo = new WeatherInfo();
            
            if (jsonObject.has("place")) {
                weatherInfo.setPlace(jsonObject.getString("place"));
            }
            if (jsonObject.has("temperature")) {
                weatherInfo.setTemperature(jsonObject.getString("temperature"));
            }
            if (jsonObject.has("humidity")) {
                weatherInfo.setHumidity(jsonObject.getString("humidity"));
            }
            if (jsonObject.has("windDirection")) {
                weatherInfo.setWindDirection(jsonObject.getString("windDirection"));
            }
            if (jsonObject.has("windScale")) {
                weatherInfo.setWindScale(jsonObject.getString("windScale"));
            }
            if (jsonObject.has("windSpeed")) {
                weatherInfo.setWindSpeed(jsonObject.getString("windSpeed"));
            }
            if (jsonObject.has("precipitation")) {
                weatherInfo.setPrecipitation(jsonObject.getString("precipitation"));
            }
            
            return weatherInfo;
            
        } catch (JSONException e) {
            Log.e(TAG, "解析天气JSON数据失败", e);
            return null;
        }
    }
    
    public void getBeijingWeather(WeatherCallback callback) {
        getWeatherInfo("北京", "朝阳", callback);
    }
    
    public void getShanghaiWeather(WeatherCallback callback) {
        getWeatherInfo("上海", "浦东", callback);
    }
}
